package com.itheima.listener;
import com.alibaba.fastjson.JSON;
import com.hmall.common.dto.Item;
import com.hmall.common.dto.ItemDoc;
import org.elasticsearch.action.delete.DeleteRequest;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;

@Component
public class SearchRabbitListener {
    @Autowired
    private RestHighLevelClient client;



    //  {"info":{},type:1}

    @RabbitListener(queues = "my.queue")
    public void listenSimpleQueueMessage(String msg) throws Exception{
//        if(1==1){return;}
        System.out.println("spring 消费者接收到消息：【" + msg + "】");
        Item item = JSON.parseObject(msg, Item.class);
        ItemDoc itemDoc = new ItemDoc(item);
        String result = JSON.toJSONString(itemDoc);
        Integer status = itemDoc.getStatus();
        if(status == 1){
            IndexRequest request = new IndexRequest("hmmall");
            request.id(itemDoc.getId()+"");
            request.source(result,XContentType.JSON);
            client.index(request, RequestOptions.DEFAULT);
        }else {
            DeleteRequest request = new DeleteRequest("hmmall", itemDoc.getId() + "");
            client.delete(request, RequestOptions.DEFAULT);
        }
    }
}
